package controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Veiling;
import database.ReadDAO;
import database.WriteDAO;

/**
 * Servlet implementation class BidController
 */
public class BidController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public BidController() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected synchronized void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ReadDAO readdao = new ReadDAO();
		int veilingid = Integer.parseInt(request.getParameter("veilingid"));
		Veiling veiling = readdao.getVeiling(veilingid);
		if(!request.getParameter("bidamount").equals("")){

			try{
				double prijs = Double.parseDouble(request.getParameter("bidamount").replaceAll(",", "."));
				double highestbid = readdao.getHighestBid(veilingid, veiling.getPrijs());
				if(prijs <= highestbid){
					//mag niet bieden
					if(veiling != null){
						request.setAttribute("veiling", veiling);
						request.setAttribute("error", "bidnothighenough");
						RequestDispatcher view = request.getRequestDispatcher("/WEB-INF/errorpages/error.jsp");
						view.forward(request, response);
						return;
					} 
				} else {
					WriteDAO writedao = new WriteDAO();
					int gebruikerid = Integer.parseInt(request.getParameter("gebruikerid"));

					writedao.addBod(gebruikerid, veilingid, prijs);
					response.sendRedirect("./VeilingController?action=fullauction&veiling="+veilingid);
					return;
				}



			} catch(NumberFormatException e){
				request.setAttribute("veiling", veiling);
				request.setAttribute("error", "nonumberbid");
				RequestDispatcher view = request.getRequestDispatcher("/WEB-INF/errorpages/error.jsp");
				view.forward(request, response);
				return;
			}
		}
		response.sendRedirect("./VeilingController?action=fullauction&veiling="+veilingid);
	}


}
